package com.hugoo.imp.buzz;

import com.hugoo.core.Conf;
import com.hugoo.core.db.mo.Record;
import com.hugoo.core.db.mo.RecordSet;
import com.hugoo.core.util.Logx;
import com.hugoo.core.util.TL;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author Lovelock.Chan
 */
public class FileUpload extends Logx{


    public File upload(String sid, String scod, HttpServletRequest request) throws FileUploadException, Exception {
        // Check that we have a file upload request
        if (ServletFileUpload.isMultipartContent(request)) {
            String spc = Conf.getBaseProp(Conf._imp_file_space);
            // Create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory(4 * 1024 * 1024, new File(spc));
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
            upload.setSizeMax(3000 * 1024 * 1024);
// Parse the request
            List<FileItem> fileItems = upload.parseRequest(request);
            //
            RecordSet<Record> rs = (RecordSet) request.getSession().getAttribute("sysuser");
            String v_userid = rs.get(0).getString("v_userid");
            //
            File f = null;
            String name = null, ext = null, est = null;
            long size = 0;
            StringBuilder sb = new StringBuilder();
            for (FileItem fi : fileItems) {//本处设计为只能上传一个附件
                if (fi.isFormField()) {
                    if ("hiduri".equalsIgnoreCase(fi.getFieldName())) {
                        request.setAttribute("hiduri", fi.getString("utf-8"));
                    } else {
                        sb.append("&").append(fi.getFieldName()).append("=").append(fmt(fi.getString("utf-8")));
                    }
                    continue;
                }
                size = fi.getSize();
                name = fi.getName();
                if (size == 0 || name == null) {
                    log.info("文件名为空或者文件对象不存在!");
                    continue;
                }
                name = name.substring(name.lastIndexOf("/") + 1).substring(name.lastIndexOf("\\") + 1);//解决名字长的问题
                //获取文件扩展类型名称如（jsp,word...）
                ext = name.substring(name.lastIndexOf("."));
                f = initFile(scod, ext);
                fi.write(f);//存储文件
            }
            ///
            HttpSession session = request.getSession();
            String rx = (String) session.getAttribute("SEP." + sid);//如果会话中存在键SEP.SID值，则采用自定义导入模式
            if (TL.isNotEmpty(rx)) {//自定义导入字段配置生命周期为一次性
                session.removeAttribute("SEP." + sid);
            }
            //----------------
            if (f != null) {
                if (sb.length() > 5) {//如果是自定义页面，会存在着自定义数据集
                    ImpDataBuzz.ref().saveAndValidationFileMeta(sid, scod, rx, v_userid, name, f.getAbsolutePath(), size, ext, sb.toString());//存储文件附加信息               
                } else {
                    ImpDataBuzz.ref().saveAndValidationFileMeta(sid, scod, rx, v_userid, name, f.getAbsolutePath(), size, ext, null);//存储文件附加信息
                }
            }
            return f;
        } else {
            log.info("无效上传方式....");
        }
        return null;
    }

    public static void main(String[] args) {
        String name = "/sd/dsf.dc";
        System.out.println(name.substring(name.lastIndexOf("/")));
    }

    private String fmt(String vl) {//采用特别替代方式
        try {
            vl = URLDecoder.decode(vl, "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            log.warn("解码错误", ex);
        }
        return vl.replaceAll("&", "x_00!01_").replaceAll("=", "x_00!02_");
    }

    private File initFile(String uuid, String ext) {
        String basepath = Conf.getBaseProp(Conf._imp_file_space);
        String mpath = TL.format(new Date(), "/yyyy/MM/");
        String bash = basepath + mpath;
        File baseFile = new File(bash);
        if (!baseFile.exists()) {
            baseFile.mkdirs();
        }
        return new File(bash + uuid + ext);
    }
}
